﻿using System;
using System.Collections.Generic;
using WickedFlame.Core.Shapes;
using WickedFlame.Core.State;

namespace WickedFlame.Core.History
{
    public class DeleteCommand : HistoryCommand
    {
        List<VectorShape> shapes;
        Dictionary<VectorShape, ShapeMemento> states;

        public DeleteCommand(ShapeList shapeList, int layerIndex)
            : base(layerIndex)
        {
            Title = "Shape deleted";

            shapes = new List<VectorShape>();
            states = new Dictionary<VectorShape, ShapeMemento>();

            foreach (VectorShape shape in shapeList.Selection)
            {
                //shapes.Add(shape.Clone());
                
                //keep reference
                shapes.Add(shape);
                if (shape is IStateCapturable)
                    states.Add(shape, ((IStateCapturable)shape).CreateMementoState());
            }
        }

        public override void Undo(ShapeList shapeList)
        {
            shapeList.UnselectAll();

            foreach (VectorShape shape in shapes)
            {
                shapeList.Add(shape);
                if (shape is IStateCapturable && states.ContainsKey(shape))
                    ((IStateCapturable)shape).ResetState(states[shape]);
            }
        }

        public override void Redo(ShapeList shapeList)
        {
            foreach (VectorShape shape in shapes)
            {
                shapeList.Remove(shape);
            }
            //int n = shapeList.Count;

            //for ( int i = n - 1; i >= 0; i-- )
            //{
            //    bool toDelete = false;
            //    VectorShape objectToDelete = shapeList[i] as VectorShape;

            //    if (objectToDelete != null)
            //    {
            //        foreach (VectorShape shape in shapes)
            //        {
            //            if (objectToDelete.ID == shape.ID)
            //            {
            //                toDelete = true;
            //                break;
            //            }
            //        }

            //        if (toDelete)
            //        {
            //            shapeList.RemoveAt(i);
            //        }
            //    }
            //}
        }
    }
}
